0f738e510709ee246ae18751770dae64870c83d4
[lhc/web/wiklou.git] / includes / SpecialUpload.php
1 <?php
2 /**
3 *
4 * @package MediaWiki
5 * @subpackage SpecialPage
6 */
7
8 /**
9 *
10 */
11 require_once 'Image.php';
12 require_once 'MacBinary.php';
13 require_once 'Licenses.php';
14 /**
15 * Entry point
16 */
17 function wfSpecialUpload() {
18 global $wgRequest;
19 $form = new UploadForm( $wgRequest );
20 $form->execute();
21 }
22
23 /**
24 *
25 * @package MediaWiki
26 * @subpackage SpecialPage
27 */
28 class UploadForm {
29 /**#@+
30 * @access private
31 */
32 var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
33 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
34 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
35 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile;
36 /**#@-*/
37
38 /**
39 * Constructor : initialise object
40 * Get data POSTed through the form and assign them to the object
41 * @param $request Data posted.
42 */
43 function UploadForm( &$request ) {
44 $this->mDestFile = $request->getText( 'wpDestFile' );
45
46 if( !$request->wasPosted() ) {
47 # GET requests just give the main form; no data except wpDestfile.
48 return;
49 }
50
51 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning');
52 $this->mReUpload = $request->getCheck( 'wpReUpload' );
53 $this->mUpload = $request->getCheck( 'wpUpload' );
54
55 $this->mUploadDescription = $request->getText( 'wpUploadDescription' );
56 $this->mLicense = $request->getText( 'wpLicense' );
57 $this->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' );
58 $this->mUploadSource = $request->getText( 'wpUploadSource' );
59 $this->mWatchthis = $request->getBool( 'wpWatchthis' );
60 wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
61
62 $this->mAction = $request->getVal( 'action' );
63
64 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
65 if( !empty( $this->mSessionKey ) &&
66 isset( $_SESSION['wsUploadData'][$this->mSessionKey] ) ) {
67 /**
68 * Confirming a temporarily stashed upload.
69 * We don't want path names to be forged, so we keep
70 * them in the session on the server and just give
71 * an opaque key to the user agent.
72 */
73 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
74 $this->mUploadTempName = $data['mUploadTempName'];
75 $this->mUploadSize = $data['mUploadSize'];
76 $this->mOname = $data['mOname'];
77 $this->mUploadError = 0/*UPLOAD_ERR_OK*/;
78 $this->mStashed = true;
79 $this->mRemoveTempFile = false;
80 } else {
81 /**
82 *Check for a newly uploaded file.
83 */
84 $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
85 $this->mUploadSize = $request->getFileSize( 'wpUploadFile' );
86 $this->mOname = $request->getFileName( 'wpUploadFile' );
87 $this->mUploadError = $request->getUploadError( 'wpUploadFile' );
88 $this->mSessionKey = false;
89 $this->mStashed = false;
90 $this->mRemoveTempFile = false; // PHP will handle this
91 }
92 }
93
94 /**
95 * Start doing stuff
96 * @access public
97 */
98 function execute() {
99 global $wgUser, $wgOut;
100 global $wgEnableUploads, $wgUploadDirectory;
101
102 /** Show an error message if file upload is disabled */
103 if( ! $wgEnableUploads ) {
104 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
105 return;
106 }
107
108 /** Various rights checks */
109 if( !$wgUser->isAllowed( 'upload' ) || $wgUser->isBlocked() ) {
110 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
111 return;
112 }
113 if( wfReadOnly() ) {
114 $wgOut->readOnlyPage();
115 return;
116 }
117
118 /** Check if the image directory is writeable, this is a common mistake */
119 if ( !is_writeable( $wgUploadDirectory ) ) {
120 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
121 return;
122 }
123
124 if( $this->mReUpload ) {
125 $this->unsaveUploadedFile();
126 $this->mainUploadForm();
127 } else if ( 'submit' == $this->mAction || $this->mUpload ) {
128 $this->processUpload();
129 } else {
130 $this->mainUploadForm();
131 }
132
133 $this->cleanupTempFile();
134 }
135
136 /* -------------------------------------------------------------- */
137
138 /**
139 * Really do the upload
140 * Checks are made in SpecialUpload::execute()
141 * @access private
142 */
143 function processUpload() {
144 global $wgUser, $wgOut, $wgUploadDirectory;
145
146 /* Check for PHP error if any, requires php 4.2 or newer */
147 if ( $this->mUploadError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
148 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
149 return;
150 }
151
152 /**
153 * If there was no filename or a zero size given, give up quick.
154 */
155 if( trim( $this->mOname ) == '' || empty( $this->mUploadSize ) ) {
156 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
157 return;
158 }
159
160 # Chop off any directories in the given filename
161 if ( $this->mDestFile ) {
162 $basename = basename( $this->mDestFile );
163 } else {
164 $basename = basename( $this->mOname );
165 }
166
167 /**
168 * We'll want to blacklist against *any* 'extension', and use
169 * only the final one for the whitelist.
170 */
171 list( $partname, $ext ) = $this->splitExtensions( $basename );
172 if( count( $ext ) ) {
173 $finalExt = $ext[count( $ext ) - 1];
174 } else {
175 $finalExt = '';
176 }
177 $fullExt = implode( '.', $ext );
178
179 if ( strlen( $partname ) < 3 ) {
180 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
181 return;
182 }
183
184 /**
185 * Filter out illegal characters, and try to make a legible name
186 * out of it. We'll strip some silently that Title would die on.
187 */
188 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
189 $nt = Title::newFromText( $filtered );
190 if( is_null( $nt ) ) {
191 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
192 return;
193 }
194 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
195 $this->mUploadSaveName = $nt->getDBkey();
196
197 /**
198 * If the image is protected, non-sysop users won't be able
199 * to modify it by uploading a new revision.
200 */
201 if( !$nt->userCanEdit() ) {
202 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
203 }
204
205 /**
206 * In some cases we may forbid overwriting of existing files.
207 */
208 $overwrite = $this->checkOverwrite( $this->mUploadSaveName );
209 if( WikiError::isError( $overwrite ) ) {
210 return $this->uploadError( $overwrite->toString() );
211 }
212
213 /* Don't allow users to override the blacklist (check file extension) */
214 global $wgStrictFileExtensions;
215 global $wgFileExtensions, $wgFileBlacklist;
216 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
217 ($wgStrictFileExtensions &&
218 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
219 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
220 }
221
222 /**
223 * Look at the contents of the file; if we can recognize the
224 * type but it's corrupt or data of the wrong type, we should
225 * probably not accept it.
226 */
227 if( !$this->mStashed ) {
228 $this->checkMacBinary();
229 $veri = $this->verify( $this->mUploadTempName, $finalExt );
230
231 if( $veri !== true ) { //it's a wiki error...
232 return $this->uploadError( $veri->toString() );
233 }
234 }
235
236 /**
237 * Provide an opportunity for extensions to add futher checks
238 */
239 $error = '';
240 if( !wfRunHooks( 'UploadVerification',
241 array( $this->mUploadSaveName, $this->mUploadTempName, &$error ) ) ) {
242 return $this->uploadError( $error );
243 }
244
245 /**
246 * Check for non-fatal conditions
247 */
248 if ( ! $this->mIgnoreWarning ) {
249 $warning = '';
250
251 global $wgCapitalLinks;
252 if( $wgCapitalLinks ) {
253 $filtered = ucfirst( $filtered );
254 }
255 if( $this->mUploadSaveName != $filtered ) {
256 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
257 }
258
259 global $wgCheckFileExtensions;
260 if ( $wgCheckFileExtensions ) {
261 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
262 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
263 }
264 }
265
266 global $wgUploadSizeWarning;
267 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
268 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
269 # value, perhaps add GB,MB and KB suffixes?
270 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize ).'</li>';
271 }
272 if ( $this->mUploadSize == 0 ) {
273 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
274 }
275
276 if( $nt->getArticleID() ) {
277 global $wgUser;
278 $sk = $wgUser->getSkin();
279 $dlink = $sk->makeKnownLinkObj( $nt );
280 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
281 }
282
283 if( $warning != '' ) {
284 /**
285 * Stash the file in a temporary location; the user can choose
286 * to let it through and we'll complete the upload then.
287 */
288 return $this->uploadWarning( $warning );
289 }
290 }
291
292 /**
293 * Try actually saving the thing...
294 * It will show an error form on failure.
295 */
296 $hasBeenMunged = !empty( $this->mSessionKey ) || $this->mRemoveTempFile;
297 if( $this->saveUploadedFile( $this->mUploadSaveName,
298 $this->mUploadTempName,
299 $hasBeenMunged ) ) {
300 /**
301 * Update the upload log and create the description page
302 * if it's a new file.
303 */
304 $img = Image::newFromName( $this->mUploadSaveName );
305 $success = $img->recordUpload( $this->mUploadOldVersion,
306 $this->mUploadDescription,
307 $this->mLicense,
308 $this->mUploadCopyStatus,
309 $this->mUploadSource,
310 $this->mWatchthis );
311
312 if ( $success ) {
313 $this->showSuccess();
314 } else {
315 // Image::recordUpload() fails if the image went missing, which is
316 // unlikely, hence the lack of a specialised message
317 $wgOut->fileNotFoundError( $this->mUploadSaveName );
318 }
319 }
320 }
321
322 /**
323 * Move the uploaded file from its temporary location to the final
324 * destination. If a previous version of the file exists, move
325 * it into the archive subdirectory.
326 *
327 * @todo If the later save fails, we may have disappeared the original file.
328 *
329 * @param string $saveName
330 * @param string $tempName full path to the temporary file
331 * @param bool $useRename if true, doesn't check that the source file
332 * is a PHP-managed upload temporary
333 */
334 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
335 global $wgUploadDirectory, $wgOut;
336
337 $fname= "SpecialUpload::saveUploadedFile";
338
339 $dest = wfImageDir( $saveName );
340 $archive = wfImageArchiveDir( $saveName );
341 $this->mSavedFile = "{$dest}/{$saveName}";
342
343 if( is_file( $this->mSavedFile ) ) {
344 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
345 wfSuppressWarnings();
346 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
347 wfRestoreWarnings();
348
349 if( ! $success ) {
350 $wgOut->fileRenameError( $this->mSavedFile,
351 "${archive}/{$this->mUploadOldVersion}" );
352 return false;
353 }
354 else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
355 }
356 else {
357 $this->mUploadOldVersion = '';
358 }
359
360 wfSuppressWarnings();
361 $success = $useRename
362 ? rename( $tempName, $this->mSavedFile )
363 : move_uploaded_file( $tempName, $this->mSavedFile );
364 wfRestoreWarnings();
365
366 if( ! $success ) {
367 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
368 return false;
369 } else {
370 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
371 }
372
373 chmod( $this->mSavedFile, 0644 );
374 return true;
375 }
376
377 /**
378 * Stash a file in a temporary directory for later processing
379 * after the user has confirmed it.
380 *
381 * If the user doesn't explicitly cancel or accept, these files
382 * can accumulate in the temp directory.
383 *
384 * @param string $saveName - the destination filename
385 * @param string $tempName - the source temporary file to save
386 * @return string - full path the stashed file, or false on failure
387 * @access private
388 */
389 function saveTempUploadedFile( $saveName, $tempName ) {
390 global $wgOut;
391 $archive = wfImageArchiveDir( $saveName, 'temp' );
392 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
393
394 $success = $this->mRemoveTempFile
395 ? rename( $tempName, $stash )
396 : move_uploaded_file( $tempName, $stash );
397 if ( !$success ) {
398 $wgOut->fileCopyError( $tempName, $stash );
399 return false;
400 }
401
402 return $stash;
403 }
404
405 /**
406 * Stash a file in a temporary directory for later processing,
407 * and save the necessary descriptive info into the session.
408 * Returns a key value which will be passed through a form
409 * to pick up the path info on a later invocation.
410 *
411 * @return int
412 * @access private
413 */
414 function stashSession() {
415 $stash = $this->saveTempUploadedFile(
416 $this->mUploadSaveName, $this->mUploadTempName );
417
418 if( !$stash ) {
419 # Couldn't save the file.
420 return false;
421 }
422
423 $key = mt_rand( 0, 0x7fffffff );
424 $_SESSION['wsUploadData'][$key] = array(
425 'mUploadTempName' => $stash,
426 'mUploadSize' => $this->mUploadSize,
427 'mOname' => $this->mOname );
428 return $key;
429 }
430
431 /**
432 * Remove a temporarily kept file stashed by saveTempUploadedFile().
433 * @access private
434 */
435 function unsaveUploadedFile() {
436 global $wgOut;
437 wfSuppressWarnings();
438 $success = unlink( $this->mUploadTempName );
439 wfRestoreWarnings();
440 if ( ! $success ) {
441 $wgOut->fileDeleteError( $this->mUploadTempName );
442 }
443 }
444
445 /* -------------------------------------------------------------- */
446
447 /**
448 * Show some text and linkage on successful upload.
449 * @access private
450 */
451 function showSuccess() {
452 global $wgUser, $wgOut, $wgContLang;
453
454 $sk = $wgUser->getSkin();
455 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
456 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
457 $dlink = $sk->makeKnownLink( $dname, $dname );
458
459 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
460 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
461 $wgOut->addHTML( $text );
462 $wgOut->returnToMain( false );
463 }
464
465 /**
466 * @param string $error as HTML
467 * @access private
468 */
469 function uploadError( $error ) {
470 global $wgOut;
471 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
472 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
473 }
474
475 /**
476 * There's something wrong with this file, not enough to reject it
477 * totally but we require manual intervention to save it for real.
478 * Stash it away, then present a form asking to confirm or cancel.
479 *
480 * @param string $warning as HTML
481 * @access private
482 */
483 function uploadWarning( $warning ) {
484 global $wgOut, $wgUser, $wgUploadDirectory, $wgRequest;
485 global $wgUseCopyrightUpload;
486
487 $this->mSessionKey = $this->stashSession();
488 if( !$this->mSessionKey ) {
489 # Couldn't save file; an error has been displayed so let's go.
490 return;
491 }
492
493 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
494 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
495
496 $save = wfMsgHtml( 'savefile' );
497 $reupload = wfMsgHtml( 'reupload' );
498 $iw = wfMsgWikiHtml( 'ignorewarning' );
499 $reup = wfMsgWikiHtml( 'reuploaddesc' );
500 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
501 $action = $titleObj->escapeLocalURL( 'action=submit' );
502
503 if ( $wgUseCopyrightUpload )
504 {
505 $copyright = "
506 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
507 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
508 ";
509 } else {
510 $copyright = "";
511 }
512
513 $wgOut->addHTML( "
514 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
515 <input type='hidden' name='wpIgnoreWarning' value='1' />
516 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
517 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
518 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense ) . "\" />
519 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
520 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis ) ) . "\" />
521 {$copyright}
522 <table border='0'>
523 <tr>
524 <tr>
525 <td align='right'>
526 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
527 </td>
528 <td align='left'>$iw</td>
529 </tr>
530 <tr>
531 <td align='right'>
532 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
533 </td>
534 <td align='left'>$reup</td>
535 </tr>
536 </tr>
537 </table></form>\n" );
538 }
539
540 /**
541 * Displays the main upload form, optionally with a highlighted
542 * error message up at the top.
543 *
544 * @param string $msg as HTML
545 * @access private
546 */
547 function mainUploadForm( $msg='' ) {
548 global $wgOut, $wgUser, $wgUploadDirectory, $wgRequest;
549 global $wgUseCopyrightUpload;
550
551 $cols = intval($wgUser->getOption( 'cols' ));
552 $ew = $wgUser->getOption( 'editwidth' );
553 if ( $ew ) $ew = " style=\"width:100%\"";
554 else $ew = '';
555
556 if ( '' != $msg ) {
557 $sub = wfMsgHtml( 'uploaderror' );
558 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
559 "<span class='error'>{$msg}</span>\n" );
560 }
561 $wgOut->addHTML( '<div id="uploadtext">' );
562 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
563 $wgOut->addHTML( '</div>' );
564 $sk = $wgUser->getSkin();
565
566
567 $sourcefilename = wfMsgHtml( 'sourcefilename' );
568 $destfilename = wfMsgHtml( 'destfilename' );
569 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
570
571 $licenses = new Licenses();
572 $license = wfMsgHtml( 'license' );
573 $nolicense = wfMsgHtml( 'nolicense' );
574 $licenseshtml = $licenses->getHtml();
575
576 $ulb = wfMsgHtml( 'uploadbtn' );
577
578
579 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
580 $action = $titleObj->escapeLocalURL();
581
582 $encDestFile = htmlspecialchars( $this->mDestFile );
583
584 $watchChecked = $wgUser->getOption( 'watchdefault' )
585 ? 'checked="checked"'
586 : '';
587
588 $wgOut->addHTML( "
589 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
590 <table border='0'>
591 <tr>
592 <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
593 <td align='left'>
594 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?"":"onchange='fillDestFilename()' ") . "size='40' />
595 </td>
596 </tr>
597 <tr>
598 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
599 <td align='left'>
600 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
601 </td>
602 </tr>
603 <tr>
604 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
605 <td align='left'>
606 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription ) . "</textarea>
607 </td>
608 </tr>
609 <tr>" );
610
611 if ( $licenseshtml != '' ) {
612 global $wgStylePath;
613 $wgOut->addHTML( "
614 <td align='right'><label for='wpLicense'>$license:</label></td>
615 <td align='left'>
616 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
617 <select name='wpLicense' id='wpLicense' tabindex='4'
618 onchange='licenseSelectorCheck()'
619 <option value=''>$nolicense</option>
620 $licenseshtml
621 </select>
622 </td>
623 </tr>
624 <tr>
625 ");
626 }
627
628 if ( $wgUseCopyrightUpload ) {
629 $filestatus = wfMsgHtml ( 'filestatus' );
630 $copystatus = htmlspecialchars( $this->mUploadCopyStatus );
631 $filesource = wfMsgHtml ( 'filesource' );
632 $uploadsource = htmlspecialchars( $this->mUploadSource );
633
634 $wgOut->addHTML( "
635 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
636 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
637 </tr>
638 <tr>
639 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
640 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
641 </tr>
642 <tr>
643 ");
644 }
645
646
647 $wgOut->addHtml( "
648 <td></td>
649 <td>
650 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
651 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
652 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
653 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
654 </td>
655 </tr>
656 <tr>
657
658 </tr>
659 <tr>
660 <td></td>
661 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
662 </tr>
663
664 <tr>
665 <td></td>
666 <td align='left'>
667 " );
668 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
669 $wgOut->addHTML( "
670 </td>
671 </tr>
672
673 </table>
674 </form>" );
675 }
676
677 /* -------------------------------------------------------------- */
678
679 /**
680 * Split a file into a base name and all dot-delimited 'extensions'
681 * on the end. Some web server configurations will fall back to
682 * earlier pseudo-'extensions' to determine type and execute
683 * scripts, so the blacklist needs to check them all.
684 *
685 * @return array
686 */
687 function splitExtensions( $filename ) {
688 $bits = explode( '.', $filename );
689 $basename = array_shift( $bits );
690 return array( $basename, $bits );
691 }
692
693 /**
694 * Perform case-insensitive match against a list of file extensions.
695 * Returns true if the extension is in the list.
696 *
697 * @param string $ext
698 * @param array $list
699 * @return bool
700 */
701 function checkFileExtension( $ext, $list ) {
702 return in_array( strtolower( $ext ), $list );
703 }
704
705 /**
706 * Perform case-insensitive match against a list of file extensions.
707 * Returns true if any of the extensions are in the list.
708 *
709 * @param array $ext
710 * @param array $list
711 * @return bool
712 */
713 function checkFileExtensionList( $ext, $list ) {
714 foreach( $ext as $e ) {
715 if( in_array( strtolower( $e ), $list ) ) {
716 return true;
717 }
718 }
719 return false;
720 }
721
722 /**
723 * Verifies that it's ok to include the uploaded file
724 *
725 * @param string $tmpfile the full path of the temporary file to verify
726 * @param string $extension The filename extension that the file is to be served with
727 * @return mixed true of the file is verified, a WikiError object otherwise.
728 */
729 function verify( $tmpfile, $extension ) {
730 #magically determine mime type
731 $magic=& wfGetMimeMagic();
732 $mime= $magic->guessMimeType($tmpfile,false);
733
734 $fname= "SpecialUpload::verify";
735
736 #check mime type, if desired
737 global $wgVerifyMimeType;
738 if ($wgVerifyMimeType) {
739
740 #check mime type against file extension
741 if( !$this->verifyExtension( $mime, $extension ) ) {
742 return new WikiErrorMsg( 'uploadcorrupt' );
743 }
744
745 #check mime type blacklist
746 global $wgMimeTypeBlacklist;
747 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
748 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
749 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
750 }
751 }
752
753 #check for htmlish code and javascript
754 if( $this->detectScript ( $tmpfile, $mime ) ) {
755 return new WikiErrorMsg( 'uploadscripted' );
756 }
757
758 /**
759 * Scan the uploaded file for viruses
760 */
761 $virus= $this->detectVirus($tmpfile);
762 if ( $virus ) {
763 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
764 }
765
766 wfDebug( "$fname: all clear; passing.\n" );
767 return true;
768 }
769
770 /**
771 * Checks if the mime type of the uploaded file matches the file extension.
772 *
773 * @param string $mime the mime type of the uploaded file
774 * @param string $extension The filename extension that the file is to be served with
775 * @return bool
776 */
777 function verifyExtension( $mime, $extension ) {
778 $fname = 'SpecialUpload::verifyExtension';
779
780 $magic =& wfGetMimeMagic();
781
782 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
783 if ( ! $magic->isRecognizableExtension( $extension ) ) {
784 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
785 return true;
786 } else {
787 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
788 return false;
789 }
790
791 $match= $magic->isMatchingExtension($extension,$mime);
792
793 if ($match===NULL) {
794 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
795 return true;
796 } elseif ($match===true) {
797 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
798
799 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
800 return true;
801
802 } else {
803 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
804 return false;
805 }
806 }
807
808 /** Heuristig for detecting files that *could* contain JavaScript instructions or
809 * things that may look like HTML to a browser and are thus
810 * potentially harmful. The present implementation will produce false positives in some situations.
811 *
812 * @param string $file Pathname to the temporary upload file
813 * @param string $mime The mime type of the file
814 * @return bool true if the file contains something looking like embedded scripts
815 */
816 function detectScript($file,$mime) {
817
818 #ugly hack: for text files, always look at the entire file.
819 #For binarie field, just check the first K.
820
821 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
822 else {
823 $fp = fopen( $file, 'rb' );
824 $chunk = fread( $fp, 1024 );
825 fclose( $fp );
826 }
827
828 $chunk= strtolower( $chunk );
829
830 if (!$chunk) return false;
831
832 #decode from UTF-16 if needed (could be used for obfuscation).
833 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
834 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
835 else $enc= NULL;
836
837 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
838
839 $chunk= trim($chunk);
840
841 #FIXME: convert from UTF-16 if necessarry!
842
843 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
844
845 #check for HTML doctype
846 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
847
848 /**
849 * Internet Explorer for Windows performs some really stupid file type
850 * autodetection which can cause it to interpret valid image files as HTML
851 * and potentially execute JavaScript, creating a cross-site scripting
852 * attack vectors.
853 *
854 * Apple's Safari browser also performs some unsafe file type autodetection
855 * which can cause legitimate files to be interpreted as HTML if the
856 * web server is not correctly configured to send the right content-type
857 * (or if you're really uploading plain text and octet streams!)
858 *
859 * Returns true if IE is likely to mistake the given file for HTML.
860 * Also returns true if Safari would mistake the given file for HTML
861 * when served with a generic content-type.
862 */
863
864 $tags = array(
865 '<body',
866 '<head',
867 '<html', #also in safari
868 '<img',
869 '<pre',
870 '<script', #also in safari
871 '<table',
872 '<title' #also in safari
873 );
874
875 foreach( $tags as $tag ) {
876 if( false !== strpos( $chunk, $tag ) ) {
877 return true;
878 }
879 }
880
881 /*
882 * look for javascript
883 */
884
885 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
886 $chunk = Sanitizer::decodeCharReferences( $chunk );
887
888 #look for script-types
889 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
890
891 #look for html-style script-urls
892 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
893
894 #look for css-style script-urls
895 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
896
897 wfDebug("SpecialUpload::detectScript: no scripts found\n");
898 return false;
899 }
900
901 /** Generic wrapper function for a virus scanner program.
902 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
903 * $wgAntivirusRequired may be used to deny upload if the scan fails.
904 *
905 * @param string $file Pathname to the temporary upload file
906 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
907 * or a string containing feedback from the virus scanner if a virus was found.
908 * If textual feedback is missing but a virus was found, this function returns true.
909 */
910 function detectVirus($file) {
911 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
912
913 $fname= "SpecialUpload::detectVirus";
914
915 if (!$wgAntivirus) { #disabled?
916 wfDebug("$fname: virus scanner disabled\n");
917
918 return NULL;
919 }
920
921 if (!$wgAntivirusSetup[$wgAntivirus]) {
922 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
923
924 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
925
926 return "unknown antivirus: $wgAntivirus";
927 }
928
929 #look up scanner configuration
930 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
931 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
932 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
933
934 $scanner= $virus_scanner; #copy, so we can resolve the pattern
935
936 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
937 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
938
939 wfDebug("$fname: running virus scan: $scanner \n");
940
941 #execute virus scanner
942 $code= false;
943
944 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
945 # that does not seem to be worth the pain.
946 # Ask me (Duesentrieb) about it if it's ever needed.
947 if (wfIsWindows()) exec("$scanner",$output,$code);
948 else exec("$scanner 2>&1",$output,$code);
949
950 $exit_code= $code; #remeber for user feedback
951
952 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
953 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
954 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
955 }
956
957 if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
958 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
959
960 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
961 else return NULL;
962 }
963 else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
964 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
965 return NULL;
966 }
967 else if ($code===AV_NO_VIRUS) {
968 wfDebug("$fname: file passed virus scan.\n");
969 return false; #no virus found
970 }
971 else {
972 $output= join("\n",$output);
973 $output= trim($output);
974
975 if (!$output) $output= true; #if ther's no output, return true
976 else if ($msg_pattern) {
977 $groups= array();
978 if (preg_match($msg_pattern,$output,$groups)) {
979 if ($groups[1]) $output= $groups[1];
980 }
981 }
982
983 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
984 return $output;
985 }
986 }
987
988 /**
989 * Check if the temporary file is MacBinary-encoded, as some uploads
990 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
991 * If so, the data fork will be extracted to a second temporary file,
992 * which will then be checked for validity and either kept or discarded.
993 *
994 * @access private
995 */
996 function checkMacBinary() {
997 $macbin = new MacBinary( $this->mUploadTempName );
998 if( $macbin->isValid() ) {
999 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1000 $dataHandle = fopen( $dataFile, 'wb' );
1001
1002 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1003 $macbin->extractData( $dataHandle );
1004
1005 $this->mUploadTempName = $dataFile;
1006 $this->mUploadSize = $macbin->dataForkLength();
1007
1008 // We'll have to manually remove the new file if it's not kept.
1009 $this->mRemoveTempFile = true;
1010 }
1011 $macbin->close();
1012 }
1013
1014 /**
1015 * If we've modified the upload file we need to manually remove it
1016 * on exit to clean up.
1017 * @access private
1018 */
1019 function cleanupTempFile() {
1020 if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) {
1021 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1022 unlink( $this->mUploadTempName );
1023 }
1024 }
1025
1026 /**
1027 * Check if there's an overwrite conflict and, if so, if restrictions
1028 * forbid this user from performing the upload.
1029 *
1030 * @return mixed true on success, WikiError on failure
1031 * @access private
1032 */
1033 function checkOverwrite( $name ) {
1034 $img = Image::newFromName( $name );
1035 if( is_null( $img ) ) {
1036 // Uh... this shouldn't happen ;)
1037 // But if it does, fall through to previous behavior
1038 return false;
1039 }
1040
1041 $error = '';
1042 if( $img->exists() ) {
1043 global $wgUser, $wgOut;
1044 if( $img->isLocal() ) {
1045 if( !$wgUser->isAllowed( 'reupload' ) ) {
1046 $error = 'fileexists-forbidden';
1047 }
1048 } else {
1049 if( !$wgUser->isAllowed( 'reupload' ) ||
1050 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1051 $error = "fileexists-shared-forbidden";
1052 }
1053 }
1054 }
1055
1056 if( $error ) {
1057 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1058 return new WikiError( $wgOut->parse( $errorText ) );
1059 }
1060
1061 // Rockin', go ahead and upload
1062 return true;
1063 }
1064
1065 }
1066 ?>